/*
 * Copyright (C) 2010-2012 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package app.transitalarm;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import app.transitalarm.model.Agency;
import app.transitalarm.model.Alarm;
import app.transitalarm.model.App;
import app.transitalarm.model.DataRetrievalException;
import app.transitalarm.model.Matcher;
import app.transitalarm.model.Stop;
import app.transitalarm.model.Vehicle;

import app.transitalarm.provider.Tables.Alarms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;

/**
 * XXX add map link.
 * XXX on list results, allow creating new alarm from list item.
 */
public final class StopViewer extends Activity {
    private static final String TAG = "StopViewer";
    private Stop s = null;
    private Agency agency = null;
    private Matcher matcher = null;
    private LayoutInflater layoutInflater;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stop_view);

        //
        if (getIntent().getData() != null) {
            final Alarm a = App.loadAlarm(getIntent().getData(), this);
            matcher = new Matcher(a);

            agency = a.getAgency();

            try {
                s = agency.getStopByCode(a.getStopCode());
            } catch (final DataRetrievalException e) {
                Android.showLongToast(this, R.string.could_not_locate_stop, a.getStopCode());
                Log.w(TAG, "Problems obtaining data for stop", e);
            }
        } else {
            final int agencyId = getIntent().getExtras().getInt(Alarms.AGENCY_ID);
            final String apiCode = getIntent().getExtras().getString(Alarms.STOP);

            matcher = null;
            agency = App.getAgency(agencyId, this);

            try {
                s = agency.getStopByCode(apiCode);
            } catch (final DataRetrievalException e) {
                Android.showLongToast(this, R.string.could_not_locate_stop, apiCode);
                Log.w(TAG, "Problems obtaining data for stop", e);
            }
        }

        //
        final TextView stationView = (TextView) findViewById(R.id.station_name);

        if (s == null) {
            stationView.setText(R.string.unknown);

            return;
        } else {
            stationView.setText(s.getName());
        }

        try {
            final ArrayList<Vehicle> vehicles = agency.getVehicles(s);

            final HashMap<Integer, TreeSet<Vehicle>> groups = new HashMap<Integer, TreeSet<Vehicle>>();

            for (final Vehicle v : vehicles) {
                final Integer groupId = Integer.valueOf(v.getGroup());

                if (!groups.containsKey(groupId)) {
                    final TreeSet<Vehicle> group = new TreeSet<Vehicle>(new Vehicle.VehicleComparator());
                    groups.put(groupId, group);
                }

                groups.get(groupId).add(v);
            }

            final VehicleAdapter adapter1 = new VehicleAdapter(this, groups.values());
            final ListView trainsView1 = (ListView) findViewById(R.id.trains1);
            trainsView1.setAdapter(adapter1);
        } catch (final DataRetrievalException e) {
            App.showError(this, "Problems obtaining vehicle data", e); //XXX this shows up alot.
        }

        /*
         * XXX last updated
        TextView dateView = (TextView) findViewById(R.id.last_updated);
        String format = android.text.format.DateFormat.is24HourFormat(this) ? T24 : T12;
        CharSequence dateStr = android.text.format.DateFormat.format(format, new Date());
        dateView.setText(dateStr);
         */
    }

    @Override
    protected void onResume() {
        super.onResume();

        layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    //    private static final String T12 = "h:mm:ss aa zz";
    //    private static final String T24 = "kk:mm:ss zz";
    private class VehicleAdapter extends BaseAdapter {
        private final ArrayList<Object> items = new ArrayList<Object>();

        public VehicleAdapter(final Context context, final Collection<TreeSet<Vehicle>> groups) {
            for (final TreeSet<Vehicle> group : groups) {
                items.add("DIVIDER");
                items.addAll(group);
            }
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(final int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(final int position) {
            return position;
        }

        @Override
        public View getView(final int position, final View v, final ViewGroup parent) {
            if ("DIVIDER".equals(getItem(position))) {
                final View view = layoutInflater.inflate(agency.getStopDividerViewId(), parent, false);

                return view;
            }

            final View view = layoutInflater.inflate(agency.getStopListItemViewId(), parent, false);
            final Vehicle t = (Vehicle) getItem(position);

            //Headsign
            String destinationName = t.getDestinationName();

            if ((matcher != null) && matcher.isInRange(t)) {
                destinationName = "*" + destinationName + "*"; // XXX Set bold, somehow?
            }

            Android.cptxt(view, R.id.headsign, destinationName);

            //Minutes
            if (t.getMinutes() != 0) {
                Android.cptxt(view, R.id.minutes, Integer.toString(t.getMinutes()));
            } else {
                Android.cptxt(view, R.id.minutes, t.getStatus());
            }

            //Route
            Android.cproute(view, R.id.line, t.getRoute());

            return view;
        }
    }
}
